package com.dynamictpm.client;

import com.dynamictpm.toolkit.http.HttpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;

/**
 * -----------------------------
 * PackageName： com.dynamictpm.client
 * ClassName：LongPollingRunnable
 * Description：长连接
 *
 * @author：it-yml CreateTime：2023-07-03
 * -----------------------------
 */
@Slf4j
public class LongPollingRunnable implements Runnable {
    private final ScheduledExecutorService executorService;
    private boolean isHealthServer = true;

    public LongPollingRunnable(ScheduledExecutorService executorService) {
        this.executorService = executorService;
    }

    @SneakyThrows
    private void checkStatus() {
        // 服务端状态不正常睡眠 30s
        if (!isHealthServer) {
            log.error("[Check config] Error. exception message, Thread sleep 30 s.");
            Thread.sleep(30000);
        }
    }

    @Override
    public void run() {
        checkStatus();
        Map<String, String> params = new HashMap<>(2);
        params.put("test", "测试");
        long readTimeoutMs = 30000 + Math.round(30000 >> 1);
        try {
            String post = HttpUtil.post("http://localhost:8888/config/listener", params, readTimeoutMs);
            setHealthServer(true);
            log.info("返回值:{}", post);
        } catch (Exception e) {
            setHealthServer(false);
        }


        executorService.execute(this);
    }

    private void setHealthServer(boolean isHealthServer) {
        this.isHealthServer = isHealthServer;
    }
}
